package IO;


import java.io.*;
import java.util.TreeSet;

/**
 * 将下列文件中的学生信息按照年龄升序排序后重新写回原文件;
 *
 * **要求:**
 *
 * 1:使用字符缓冲流完成;
 *
 * 2:每次循环读取一行信息
 *
 * 3:写数据的时候换行使用newLine方法;
 *
 * **注意:**
 *
 * ①文件中不要有多余的空行
 *
 * ②怎么按照年龄排序呢?    想想能不能使用Student对象将姓名和年龄封装一下
 */
public class Test03 {
    public static void main(String[] args) throws IOException {
        TreeSet<Student> treeSet = new TreeSet<>((o1, o2) -> o1.getAge()- o2.getAge());
        BufferedReader bufferedReader = new BufferedReader(new FileReader("1.txt"));
        while (true) {
            String line = bufferedReader.readLine();
            if (line != null) {
                String name = line.split(",")[0];
                Integer age = Integer.valueOf(line.split(",")[1]);
                treeSet.add(new Student(name,age));
            }else {
                break;
            }
        }
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("2.txt"));
        for (Student stu : treeSet) {
            String name = stu.getName();
            String age = String.valueOf(stu.getAge());
            bufferedWriter.write(name+","+age);
            bufferedWriter.newLine();
        }
        bufferedWriter.flush();

        bufferedReader.close();
        bufferedWriter.close();
    }
}
